package com.ronghuanet.car.service.impl;

import com.ronghuanet.basic.service.IBaiduAiService;
import com.ronghuanet.basic.service.impl.BaseServiceImpl;
import com.ronghuanet.basic.util.AjaxResult;
import com.ronghuanet.basic.util.VelocityUtils;
import com.ronghuanet.car.CarOprDto;
import com.ronghuanet.car.domain.Car;
import com.ronghuanet.car.domain.CarDetail;
import com.ronghuanet.car.domain.CarOnlineAuditLog;
import com.ronghuanet.car.domain.CarType;
import com.ronghuanet.car.es.doc.CarDoc;
import com.ronghuanet.car.es.repository.CarDocRepository;
import com.ronghuanet.car.mapper.CarDetailMapper;
import com.ronghuanet.car.mapper.CarMapper;
import com.ronghuanet.car.mapper.CarOnlineAuditLogMapper;
import com.ronghuanet.car.mapper.CarTypeMapper;
import com.ronghuanet.car.service.ICarService;
import com.ronghuanet.org.domain.Shop;
import com.ronghuanet.org.mapper.ShopMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-09-08
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<Car> implements ICarService {

    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarDetailMapper carDetailMapper;

    @Autowired
    private IBaiduAiService baiduAiService;

    @Autowired
    private CarOnlineAuditLogMapper logMapper;

    @Autowired
    private CarDocRepository carDocRepository;

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private CarTypeMapper carTypeMapper;
    @Override
    @Transactional
    public void add(@RequestParam(required = true) Car car) {
        CarDetail carDetail = car.getCarDetail();
        //审核
        String text = car.getTitle() +" "+ carDetail.getInfo();
        AjaxResult ajaxResult = AjaxResult.me();//baiduAiService.audit(text, car.getCover(), null);
        CarOnlineAuditLog log = new CarOnlineAuditLog();  //审核日志() 上下线日志
        log.setAuditTime(new Date());
        if (ajaxResult.isSuccess()){
            log.setState(1);
            log.setNote("系统审核通过！");
        }else
        {
            log.setState(-1); //
            log.setNote("系统审核失败！"+ajaxResult.getResult());
        }

        //保存car的信息
        car.setCreatetime(new Date());
        car.setState(0L); //0 1
        car.setAuditstate(log.getState()); //0 1 -1
        carMapper.save(car);
        //保存cardetail信息
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
        carDetailMapper.save(carDetail);


        //上面没有carId，需要保存后获取再保存日志
        log.setCarId(car.getId());
        logMapper.save(log);
    }


    /*
    @Override
    @Transactional
    public void add(Car car) {
        //保存car的信息
        car.setCreatetime(new Date());
        car.setState(0L); //0 1
        car.setAuditstate(0); //0 1 -1
        carMapper.save(car);
        //保存cardetail信息

        CarDetail carDetail = car.getCarDetail();
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
        carDetailMapper.save(carDetail);


        //审核
        String text = car.getTitle() +" "+ carDetail.getInfo();
        AjaxResult ajaxResult = AjaxResult.me();//baiduAiService.audit(text, car.getCover(), null);


        CarOnlineAuditLog log = new CarOnlineAuditLog();  //审核日志() 上下线日志
        log.setCarId(car.getId());
        log.setAuditTime(new Date());
        if (ajaxResult.isSuccess()){
            log.setState(1);
            log.setNote("系统审核通过！");
        }else
        {
            log.setState(-1); //
            log.setNote("系统审核失败！"+ajaxResult.getResult());
        }
        logMapper.save(log);



        //修改审核状态
        car.setAuditstate(log.getState());
        carMapper.update(car);

    }*/

    @Override
    public void update(Car car) {
        super.update(car);

        //也要处理自动审核
    }

    @Override
    public void onsale(CarOprDto carOprDto) {
        //参数判断
        List<Long> ids = carOprDto.getIds();
        if (ids==null || ids.size()<1)
            throw new RuntimeException("系统异常，参数不对！");

        //es中加入数据
       /* List<CarDoc> carDocs =buildCarDocs(ids);
        carDocRepository.saveAll(carDocs);*/

        //不要操作es了，操作上线详情表  type=onsale/offsale;  ---转换为本地事务

        //canal监控这种表进行es进行操作


        //修改数据库状态和上架时间
        carMapper.onsale(ids);
        //添加日志
        addLogs(carOprDto,2);

        //页面静态化实现
        staticPages(carOprDto.getIds());

    }

    private void staticPages(List<Long> carIds) {
        //每个车要有一个静态化页面
        carIds.forEach(carId->{

            //模型 car
            Car car = carMapper.loadById(carId);

            //模板
            String tmplatePath = this.getClass().getClassLoader().getResource("").getPath()
                    +"/templates/carDetail.vm";
            System.out.println(tmplatePath);

            //静态化页面生成的路径
            String protalWebsitePath = "D:\\IdeaProjects\\ronghuanet-car-websites\\ronghuanet-car-portal\\details\\";
            String htmlFilePath =protalWebsitePath + carId+ ".html";
            VelocityUtils.staticByTemplate(car,tmplatePath,htmlFilePath);
        });
    }

    private List<CarDoc> buildCarDocs(List<Long> ids) {
        List<CarDoc> result = new ArrayList<>();
        ids.forEach(carId->{
            result.add(buildCarDoc(carId));
        });
        return result;
    }

    private CarDoc buildCarDoc(Long carId) {
        Car car = carMapper.loadById(carId);//数据库
        CarDoc carDoc = new CarDoc();//es
        carDoc.setId(carId);
        carDoc.setTitle(car.getTitle());
        carDoc.setCover(car.getCover());
        carDoc.setSaleprice(car.getSaleprice());
        carDoc.setCostprice(car.getCostprice());
        carDoc.setIsnew(car.getIsnew());
        carDoc.setReigstertime(car.getReigstertime());
        carDoc.setMileage(car.getMileage());
        Shop shop = shopMapper.loadById(car.getShopId());
        carDoc.setShopId(shop.getId());
        carDoc.setShopName(shop.getName());
        carDoc.setShopAdress(shop.getAddress());
        carDoc.setOnsaletime(car.getOnsaletime());
        carDoc.setCosteffective(car.getCosteffective());
        carDoc.setRushsale(car.getRushsale());
        carDoc.setQuasinewcar(car.getQuasinewcar());
        carDoc.setTransitivecountry(car.getTransitivecountry());
        CarType carType = carTypeMapper.loadById(car.getTypeId());
        carDoc.setTypeId(carType.getId());
        carDoc.setTypeName(carType.getName());
        CarDetail detail = carDetailMapper.loadByCarId(carId);
        if (detail!=null)
         carDoc.setCarInfo(detail.getInfo());
        return carDoc;
    }

    @Override
    public void offsale(CarOprDto carOprDto) {
        //参数判断
        List<Long> ids = carOprDto.getIds();
        if (ids==null || ids.size()<1)
            throw new RuntimeException("系统异常，参数不对！");
        //es中删除数据  只给他设置id   ????我认为可以
        List<CarDoc> carDocs = new ArrayList<>();
        ids.forEach(id->{
            CarDoc doc = new CarDoc();
            doc.setId(id);
        });
        carDocRepository.deleteAll(carDocs);

        //修改数据库状态和下架时间
        carMapper.offsale(carOprDto.getIds());
        //添加日志
        addLogs(carOprDto,3);
    }

    private void addLogs(CarOprDto carOprDto,  int state) {
        List<CarOnlineAuditLog> logs = new ArrayList<>();
        carOprDto.getIds().forEach(id -> {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setState(state);//上架
            log.setAuditId(carOprDto.getOperatorId());
            log.setAuditTime(new Date());
            if (state==2)
                 log.setNote(carOprDto.getOperatorName() + "对id为" + id + "进行了上架！");
            else if (state==3)
                log.setNote(carOprDto.getOperatorName() + "对id为" + id + "进行了下架！");
            logs.add(log);
        });

        logMapper.bulkSave(logs);
    }
}
